import { Controller, Post, Body, Get, Patch, Param, ParseIntPipe, Delete } from '@nestjs/common';
import { CategoryService } from './category.service';
import { CommonObjectProps, CommonResponse } from '../../types/obj-type';
import { responseWrapper } from '../../utils';

@Controller('category')
export class CategoryController {
  constructor(private readonly bookService: CategoryService) {}

  @Post()
  async addBook(@Body() book: CommonObjectProps): Promise<CommonResponse> {
    try {
      const res = await this.bookService.addBook(book);
      return responseWrapper(res);
    } catch (error) {
      return responseWrapper(error, true);
    }
  }

  @Get()
  async books(): Promise<CommonResponse> {
    try {
      const res = await this.bookService.books();
      return responseWrapper(res);
    } catch (error) {
      return responseWrapper(error, true);
    }
  }

  @Get(':id')
  async getBook(@Param('id', new ParseIntPipe()) id: number): Promise<CommonResponse> {
    try {
      const res = await this.bookService.getBook(id);
      if (!res) throw new Error('帖子不存在');
      return responseWrapper(res);
    } catch (error) {
      return responseWrapper(error, true);
    }
  }

  @Patch(':id')
  async update(
    @Param('id', new ParseIntPipe()) id: number,
    @Body() data: CommonObjectProps,
  ): Promise<CommonResponse> {
    try {
      const res = await this.bookService.update(id, data);
      return responseWrapper(res);
    } catch (error) {
      return responseWrapper(error, true);
    }
  }

  @Delete(':id')
  async delete(@Param('id', new ParseIntPipe()) id: number): Promise<CommonResponse> {
    try {
      const res = await this.bookService.delete(id);
      return responseWrapper(res);
    } catch (error) {
      return responseWrapper(error, true);
    }
  }
}
